﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Csla;
using Csla.Data;

namespace Asah.SiteWorx.Commerce
{
    [Serializable()]
    public class OrderItems : BusinessListBase<OrderItems, OrderItem>
    {
        #region Business Methods

        public OrderItem GetOrderItem(int orderItemId)
        {
            foreach(OrderItem child in this)
            {
                if (child.ID == orderItemId)
                    return child;
            }
            return null;
        }

        public OrderItem AddNew()
        {
            OrderItem child = OrderItem.NewOrderItem();
            base.Add(child);
            return child;
        }

        public void Remove(int orderItemId)
        {
            foreach (OrderItem child in this)
            {
                if (child.ID == orderItemId)
                {
                    Remove(child);
                    return;
                }
            }
        }

        public bool Contains(int orderItemId)
        {
            foreach (OrderItem child in this)
            {
                if (child.ID == orderItemId)
                    return true;
            }
            return false;
        }

        public bool ContainsDeleted(int orderItemId)
        {
            foreach (OrderItem child in this)
            {
                if (child.ID == orderItemId) 
                    return true;
            }
            return false;
        }
        
        #endregion

        #region Factory Methods

        internal static OrderItems NewOrderItems()
        {
            return new OrderItems();
        }

        internal static OrderItems GetOrderItems(SafeDataReader dr)
        {
            return new OrderItems(dr);
        }

        private OrderItems()
        {
            MarkAsChild();
        }

        private OrderItems(SafeDataReader dr)
        {
            Fetch(dr);
            MarkAsChild();
        }
       
        #endregion

        #region Data Access

        private void Fetch(SafeDataReader dr)
        {
            this.RaiseListChangedEvents = false;
            while (dr.Read())
            {
                this.Add(OrderItem.GetOrderItem(dr));
            }
            this.RaiseListChangedEvents = true;
        }

        internal void Insert(Order order)
        {
            this.RaiseListChangedEvents = false;

            // add any current child objects
            foreach (OrderItem child in this)
            {
                child.Insert(order);
            }
            this.RaiseListChangedEvents = true;
        }

        #endregion
    }
   
}
